import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';

part 'sign_in_http.g.dart';

class SignInHttpDemo extends StatefulWidget {
  const SignInHttpDemo({Key? key, this.httpClient}) : super(key: key);

  final http.Client? httpClient;

  @override
  _SignInHttpDemoState createState() => _SignInHttpDemoState();
}

class _SignInHttpDemoState extends State<SignInHttpDemo> {
  FormData formData = FormData();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sign in Form'),
      ),
      body: Form(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              ...[
                TextFormField(
                  autofocus: true,
                  textInputAction: TextInputAction.next,
                  decoration: const InputDecoration(
                    filled: true,
                    hintText: 'Your email address',
                    labelText: 'Email',
                  ),
                  onChanged: (value) {
                    formData.email = value;
                  },
                ),
                TextFormField(
                  decoration: const InputDecoration(
                    filled: true,
                    labelText: 'Password',
                  ),
                  obscureText: true,
                  onChanged: (value) {
                    formData.password = value;
                  },
                ),
                TextButton(
                  onPressed: () async {
                    // Use a JSON encoded string to send
                    var result = await widget.httpClient!.post(
                      Uri.parse('https://example.com/sign'),
                      body: json.encode(formData.toJson()),
                      headers: {'content-type': 'application/json'},
                    );

                    if (result.statusCode == 200) {
                      _showDialog('Successfully signed in.');
                    } else if (result.statusCode == 401) {
                      _showDialog('Unable to sign in.');
                    } else {
                      _showDialog('Something went wrong. Please try again.');
                    }
                  },
                  child: const Text('Sign in'),
                ),
              ]
            ],
          ),
        ),
      ),
    );
  }

  void _showDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }
}

@JsonSerializable()
class FormData {
  String? email;
  String? password;

  FormData({
    this.email,
    this.password,
  });

  factory FormData.fromJson(Map<String, dynamic> json) =>
      _$FormDataFromJson(json);

  Map<String, dynamic> toJson() => _$FormDataToJson(this);
}
